/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.components.defaults.cards

import cn.nkpro.elcube.annotation.NkNote
import cn.nkpro.elcube.co.spel.NkSpELManager
import cn.nkpro.elcube.docengine.EnumDocClassify
import cn.nkpro.elcube.docengine.NkAbstractCard
import cn.nkpro.elcube.docengine.model.DocDefIV
import cn.nkpro.elcube.docengine.model.DocHV
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component

@Order(2003)
@NkNote("数据抓取")
@Component("NkCardDataCollector")
class NkCardDataCollector extends NkAbstractCard<Data,Def> {

    @Autowired
    private NkSpELManager spELManager

    @Override
    Data calculate(DocHV doc, Data data, DocDefIV defIV, Def d, boolean isTrigger, Object options) {

        if(d.collectSpEL){
            if(d.watchSpEL){
                def invoke = spELManager.invoke(d.watchSpEL, doc)
                if(!StringUtils.equals(invoke as String, data.watched)){
                    data.collected = spELManager.invoke(d.collectSpEL, doc)
                }
            }else{
                data.collected = spELManager.invoke(d.collectSpEL, doc)
            }
        }
        return super.calculate(doc, data, defIV, d, isTrigger, options) as Data
    }

    static class Def implements Serializable{
        String watchSpEL
        String collectSpEL
        String vueTemplate
        Boolean allowViewSource
    }

    static class Data implements Serializable{
        String watched
        Object collected
    }
}
